#!/usr/bin/env ruby

first, second = *ARGV

abort "Usage: script/merge_users [FIRST_EMAIL] [SECOND_EMAIL]" if first.nil? || second.nil?

ENV["RAILS_ENV"] ||= "production"
require_relative "../config/environment"

first_user  = User.find_by_email!(first)
second_user = User.find_by_email!(second)

def choose_from_two(first, second, term:)
  puts "Which #{term} do you want to keep? (1/2)"
  puts "1. #{first}"
  puts "2. #{second}"
  choose_one(first, second)
end

def choose_one(first, second)
  case $stdin.gets.chomp
  when "1" then first
  when "2" then second
  else
    puts "You must choose 1 or 2"
    choose_one(first, second)
  end
end

email = choose_from_two(first_user.email, second_user.email, term: "email")
handle = choose_from_two(first_user.handle, second_user.handle, term: "handle")

if email == first_user.email
  chosen_user = first_user
  other_user  = second_user
else
  chosen_user = second_user
  other_user  = first_user
end

puts "Merging #{chosen_user.email}/#{handle}..."

(other_user.rubygems - chosen_user.rubygems).each do |rubygem|
  puts "Merging ownership for #{rubygem.name}..."
  ownership = rubygem.ownerships_including_unconfirmed.find_by_user_id(other_user.id)
  ownership.user = chosen_user
  ownership.save!
end

other_user.destroy

chosen_user.handle = handle
chosen_user.save!

puts "Done!"
